package f9window;

import orderdata.OrderData;
import orderdata.OrderDataSource;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;

import java.time.Duration;

public class Window1 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        SingleOutputStreamOperator<OrderData> data = env.addSource(new OrderDataSource())
                .assignTimestampsAndWatermarks(WatermarkStrategy.
                        <OrderData>forBoundedOutOfOrderness(Duration.ofSeconds(1))
                        .withTimestampAssigner(new SerializableTimestampAssigner<OrderData>() {
                            @Override
                            public long extractTimestamp(OrderData orderData, long l) {
                                return orderData.order_date;
                            }
                        })
                );
        data.print();

        KeyedStream<OrderData, String> orderDataStringKeyedStream = data.keyBy(new KeySelector<OrderData, String>() {

            @Override
            public String getKey(OrderData orderData) throws Exception {
                return orderData.category;
            }
        });

        orderDataStringKeyedStream.window(TumblingEventTimeWindows.of(Time.seconds(5)))
                .reduce(new ReduceFunction<OrderData>() {
                    @Override
                    public OrderData reduce(OrderData orderData, OrderData t1) throws Exception {
                        return new OrderData(
                                Math.max(orderData.order_date,t1.order_date),
                                orderData.category,
                                orderData.region,
                                orderData.user_id,
                                orderData.order_count+t1.order_count,
                                orderData.total_amount+t1.total_amount
                        );
                    }
                }).print("窗口统计");
        env.execute();
    }
}
